<template>
  <el-card>
    <el-table :data="shoplist" stripe border style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="expand-content">
            <el-form-item label="店铺名称">
              <span>{{ scope.row.name }}</span>
            </el-form-item>
            <el-form-item label="店铺地址">
              <span>{{ scope.row.address }}</span>
            </el-form-item>
            <el-form-item label="店铺介绍">
              <span>{{ scope.row.description }}</span>
            </el-form-item>
            <el-form-item label="店铺ID">
              <span>{{ scope.row.id }}</span>
            </el-form-item>
            <el-form-item label="联系电话">
              <span>{{ scope.row.phone }}</span>
            </el-form-item>
            <el-form-item label="评分">
              <span>{{ scope.row.rating }}</span>
            </el-form-item>
            <el-form-item label="销售量">
              <span>{{ scope.row.recent_order_num }}</span>
            </el-form-item>
            <el-form-item label="分类">
              <span>{{ scope.row.category }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="店铺名称" width="200"> </el-table-column>
      <el-table-column prop="address" label="店铺地址" width="380"> </el-table-column>
      <el-table-column prop="description" label="店铺介绍"> </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="primary" plain @click="addFood(scope.row)">添加食品</el-button>
          <el-button size="mini" type="danger" plain @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="offset" :page-sizes="[20, 25, 30, 35, 40]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="count"> </el-pagination>
    <!-- 编辑店铺信息对话框 -->
    <el-dialog title="修改店铺信息" :visible.sync="dialogVisibleEdit" width="50%">
      <el-form ref="form" :model="selctTable" label-width="80px">
        <el-form-item label="店铺名称">
          <el-input v-model="selctTable.name"></el-input>
        </el-form-item>
        <!-- 搜索地址 -->
        <el-form-item label="店铺地址">
          <el-autocomplete v-model="selctTable.address" :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelect" style="width:100%;"></el-autocomplete>
          <span>当前城市: {{ city.name }}</span>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="selctTable.phone"></el-input>
        </el-form-item>
        <el-form-item label="店铺介绍">
          <el-input v-model="selctTable.description"></el-input>
        </el-form-item>
        <!-- 店铺分类 -->
        <el-form-item label="店铺分类">
          <el-cascader v-model="selectedCategory" :options="categoryOptions" @change="handleChangeOptins"></el-cascader>
        </el-form-item>
        <!-- 店铺图片 -->
        <el-form-item label="店铺图片">
          <el-upload class="avatar-uploader" :action="baseURL + '/v1/addimg/shop'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="selctTable.image_path" :src="baseImgPath + selctTable.image_path" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 确定 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="updateShop">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { cityGuess, getRestaurantCount, foodCategory, updateResturant, deleteResturant } from '../api/index'
import request from '../api/axiosApi'
import { baseImgPath, baseURL } from '../api/env'
export default {
  data() {
    return {
      baseURL,
      baseImgPath,
      shoplist: [],
      city: {},
      count: 0,
      limit: 20,
      offset: 1,
      dialogVisibleEdit: false,
      selctTable: {},
      selectedCategory: [],
      categoryOptions: []
    }
  },
  created() {
    this.initdata()
  },
  methods: {
    async initdata() {
      try {
        // 获取定位城市参数
        const res = await cityGuess()
        this.city = res.data
        const countData = await getRestaurantCount()
        if (countData.data.status === 1) {
          this.count = countData.data.count
        } else {
          throw new Error('获取数据失败')
        }
        this.getResturants()
      } catch (error) {
        console.log('获取数据失败', error)
      }
    },
    async getResturants() {
      const { latitude, longitude } = this.city
      // 获取餐馆列表
      const res = await request.get(`/shopping/restaurants?latitude=${latitude}&longitude=${longitude}&limit=${this.limit}&offset=${this.offset}`)
      this.shoplist = res.data
    },
    handleSizeChange(pageSize) {
      this.limit = pageSize
      this.getResturants()
    },
    handleCurrentChange(pageNum) {
      this.offset = pageNum
      this.getResturants()
    },
    // 编辑餐馆信息
    handleEdit(row) {
      this.selctTable = row
      this.selectedCategory = row.category.split('/')
      if (!this.categoryOptions.length) {
        this.getCategory()
      }
      this.dialogVisibleEdit = true
    },
    // 获取搜索地址
    async querySearchAsync(queryStr, cd) {
      if (queryStr) {
        const { data } = await request.get(`/v1/pois?type='search'&city_id=${this.city.id}&keyword=${queryStr}`)
        console.log(data)
        // console.log(cityList)
        if (data instanceof Array) {
          data.map(item => {
            item.value = item.address
            return item
          })
          cd(data)
        }
        try {
        } catch (error) {
          console.log(error)
        }
      }
    },
    // 获取商品分类
    async getCategory() {
      try {
        const { data: res } = await foodCategory()
        res.forEach(item => {
          const adddnew = {
            value: item.name,
            label: item.name,
            children: []
          }
          item.sub_categories.forEach((subitem, index) => {
            if (index === 0) {
              return
            }
            adddnew.children.push({
              value: subitem.name,
              label: subitem.name
            })
          })
          this.categoryOptions.push(adddnew)
        })
        console.log(res)
      } catch (error) {
        console.log('获取商铺种类失败')
      }
    },
    handleSelect() {},
    handleChangeOptins(e) {
      console.log(e)
    },
    handleAvatarSuccess(res, file) {
      if (res.status === 1) {
        this.selctTable.image_path = res.image_path
      } else {
        this.$message.error('上传图片失败')
      }
    },
    beforeAvatarUpload(file) {
      const isType = file.type === 'image/jpeg' || file.type === 'image/png'
      const isSize2M = file.size / 1024 / 1024 < 2
      if (!isType) {
        this.$message.error('上传头像图片只能是JPG格式')
      }
      if (!isSize2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
    },
    // 提交修改商铺信息
    async updateShop() {
      this.dialogVisibleEdit = false
      try {
        this.selctTable.category = this.selectedCategory.join('/')
        const { data: res } = await updateResturant(this.selctTable)
        if (res.status === 1) {
          this.$message.success('修改商铺信息成功')
          this.getResturants()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('修改商铺失败', error)
      }
    },
    // 点击添加按钮跳转到
    addFood(row) {
      this.$router.push({ path: 'addGoods', query: { restaurant_id: row.id } })
    },
    // 删除商铺
    async handleDelete(index, row) {
      try {
        const { data: res } = await deleteResturant(row.id)
        if (res.status === 1) {
          this.$message.success(res.message)
          this.getResturants()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('删除无效', error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.expand-content {
  padding: 20px 40px;
  display: flex;
  flex-wrap: wrap;
  /deep/.el-form-item {
    width: 50%;
    margin: 0;
    .el-form-item__label {
      margin-right: 70px;
      color: #99a9bf;
    }
  }
}
</style>
